// stores/modules/chat.js
import {
	defineStore
} from 'pinia'
import {
	ref,
	computed
} from 'vue' // 添加 computed 导入
import chatApi from '@/api/modules/chat'

export const useChatStore = defineStore('chat', () => {
	// 状态定义
	const chatSessions = ref({})
	const loading = ref(false)
	const currentDeviceId = ref(null)

	// 计算属性
	const messages = computed(() => {
		return chatSessions.value[currentDeviceId.value] || []
	})

	// 设置当前设备ID并加载历史记录
	function setCurrentDeviceId(deviceId) {
		currentDeviceId.value = deviceId
		if (!chatSessions.value[deviceId]) {
			loadChatHistory(deviceId)
		}
	}

	// 加载聊天历史
	// 修改 loadChatHistory 函数
	function loadChatHistory(deviceId) {
		try {
			const userId = uni.getStorageSync('userId')
			const storageKey = `chat_history_${deviceId}_${userId}`
			const history = uni.getStorageSync(storageKey)
			if (history) {
				chatSessions.value[deviceId] = JSON.parse(history)
			} else {
				chatSessions.value[deviceId] = []
			}
			console.log('加载历史记录:', chatSessions.value[deviceId])
		} catch (error) {
			console.error('加载聊天历史失败:', error)
			chatSessions.value[deviceId] = []
		}
	}
	//保存聊天记录
	// 修改 saveChatHistory 函数
	function saveChatHistory() {
		if (!currentDeviceId.value) return
		try {
			const userId = uni.getStorageSync('userId')
			const storageKey = `chat_history_${currentDeviceId.value}_${userId}`
			const sessionData = JSON.stringify(chatSessions.value[currentDeviceId.value])
			uni.setStorageSync(storageKey, sessionData)
			console.log('保存聊天历史成功')
		} catch (error) {
			console.error('保存聊天历史失败:', error)
		}
	}

	// 发送消息
	async function sendMessage(messageData) {
		if (!currentDeviceId.value || loading.value) return
		loading.value = true

		const currentSession = chatSessions.value[currentDeviceId.value] || []

		try {
			// 添加用户消息
			const userMsg = {
				id: Date.now(),
				role: 'user',
				content: messageData.message,
				timestamp: Date.now()
			}
			currentSession.push(userMsg)
			chatSessions.value[currentDeviceId.value] = currentSession
			saveChatHistory()

			// 发送消息到服务器
			const res = await uni.request({
				url: 'http://localhost:8081/api/chat/send',
				method: 'POST',
				header: {
					'Content-Type': 'application/json',
					'Authorization': uni.getStorageSync('token'),
					'User-Id': uni.getStorageSync('userId')
				},
				data: messageData
			})

			// 处理响应
			if (res.statusCode === 200 && res.data?.message) {
				const aiMsg = {
					id: Date.now() + 1,
					role: 'assistant',
					content: res.data.message,
					timestamp: Date.now()
				}
				currentSession.push(aiMsg)
				chatSessions.value[currentDeviceId.value] = currentSession
				saveChatHistory()
				return res.data
			}
			throw new Error('消息发送失败')
		} catch (error) {
			console.error('发送消息失败:', error)
			throw error
		} finally {
			loading.value = false
		}
	}

	// 清空聊天记录
	function clearChat() {
		if (!currentDeviceId.value) return
		chatSessions.value[currentDeviceId.value] = []
		uni.removeStorageSync(`chat_history_${currentDeviceId.value}`)
	}

	function addMessage(message) {
		if (!currentDeviceId.value) return

		const currentSession = chatSessions.value[currentDeviceId.value] || []
		currentSession.push(message)
		chatSessions.value[currentDeviceId.value] = currentSession
		saveChatHistory()
	}


	return {
		messages,
		loading,
		currentDeviceId,
		sendMessage,
		setCurrentDeviceId,
		clearChat,
		addMessage,
		loadChatHistory,
		saveChatHistory
	}
})